// pages/box/box.js
var app = getApp()
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isShow: false,
		activity: '', //活动id
		loading: false,
		show: false,
		payType: 'wechat',
		move: 0,
		right: false,
		showMsg: false,
		balance: null,
		goodsPrice: null,
		boxFace: '',
		boxTop: '',
		ficationLOGO: '',
		ficationName: '',
		company: '',
		// //////
		btnDisable: false, //用户点击换一盒的时候，赋值为true，将页面其他3个按钮禁用
		goodsList: [], //商品列表
		num: 0,
		userGoodsList: [], //用户已拥有商品（用户订单）
		rollGoods: [], //  roll出去的两个商品，用于展示的roll出去的两个商品
		resultGoods: {}, //预抽取的盒子
		demolition: ''
	},
	getDetail: function(id) {
		var _this = this
		wx.request({
			url: app.globalData.url+'/v1/goods/details',
			method: 'GET',
			data: {
				openid: app.globalData.openId,
				fid: id
			},
			success: function(r) {
				r = r.data
				if (r.code == 0) {
					_this.setData({
						boxFace: r.data.image[2].url,
						ficationName: r.data.items.fication_name,
						goodsPrice: r.data.items.gprice,
						demolition: r.data.items.demolition
					})
				} else {
					wx.showToast({
						title: r.data.message,
						icon: 'none',
						duration: 2000
					})
				}
			}
		})
	},
	getBalance: function() {
		var _this = this
		wx.request({
			url: app.globalData.url+'/v1/payment/show',
			method: 'GET',
			data: {
				openid: app.globalData.openId
			},
			success: function(r) {
				r = r.data
				if (r.code == 0) {
					_this.setData({
						balance: Number(r.data.money)
					})
				} else {
					wx.showToast({
						title: r.data.message,
						icon: 'none',
						duration: 2000
					})
				}
			}
		})
	},
	getGoodsList: function(id) { //获取商品
		wx.showToast({
			icon: 'loading',
			title: 'loading...',
			duration: 60000,
			mask: true
		})
		var _this = this
		wx.request({
			url: app.globalData.url+'/v1/goods/fication',
			method: 'GET',
			data: {
				fid: id
			},
			success: function(r) {

				_this.setData({
					goodsList: r.data.data,
					// goodsPrice: Number(r.data.data[0].price)
				})
				_this.getUserGoodsList()

			}
		})
	},
	getUserGoodsList: function() { //获取用户已有商品（用户订单）
		var _this = this
		wx.request({
			url: app.globalData.url+'/v1/order/list',
			method: 'GET',
			data: {
				size: 1000,
				current: 1,
				openid: app.globalData.openId
			},
			success: function(r) {
				// 先去重，再赋值！！！！
				var arr = []
				r.data.data.items.forEach(item => {
					if (arr.indexOf(item.goods_id) == -1) {
						arr.push(item.goods_id)
					}
				})
				_this.setData({
					userGoodsList: arr
				})
				_this.randomGoods()
			}
		})
	},
	randomGoods() {
		this.setData({
			num: 0,
			rollGoods: [],
			rollGoodsShow: []
		})
		var goodsArr = this.data.goodsList.filter(item => { //临时的商品列表
			return item.goods_name.indexOf('隐藏') == -1
		})
		var hideGood = this.data.goodsList.filter(item => { //隐藏款
			return item.goods_name.indexOf('隐藏') != -1
		})[0]
		console.log('隐藏款:')
		console.log(hideGood)
		goodsArr.sort(function(a, b) { //商品按照库存排序
			return b.stock - a.stock
		})
		console.log('商品列表：')
		console.log(goodsArr)
		console.log('订单列表')
		console.log(this.data.userGoodsList)
		for (var i = 0; i < goodsArr.length; i++) {
			for (var k = 0; k < this.data.userGoodsList.length; k++) {
				if (goodsArr[i].id == this.data.userGoodsList[k]) { //用商品列表和用户已有商品数组匹配
					goodsArr[i].have = true //如果匹配到，给该商品更改属性have = true
				}
			}
		}
		goodsArr = goodsArr.filter(item => { // 过滤掉have == true的商品
			return !item.have
		})
		console.log('用户没抽到过的商品：')
		console.log(goodsArr)
		if (goodsArr.length == 0) {
			console.log('用户所有基础款抽完！')
			var num = 1 //给定一个数
			var randomNum = Math.floor(Math.random() * 26) //隐藏款id为25分之1
			if (num == randomNum) {
				//抽到隐藏款
				this.setData({
					resultGoods: hideGood
				})
			} else {
				goodsArr = this.data.goodsList.filter(item => { //除了隐藏款的商品列表
					return item.goods_name.indexOf('隐藏') == -1
				})
				console.log('没抽到隐藏款后的商品列表')
				console.log(goodsArr)
				var idx = Math.floor(Math.random() * (this.data.goodsList.length - 1))
				this.setData({
					resultGoods: goodsArr[idx] //没有抽到隐藏就从商品列表里随机分配一个
				})
			}
		} else {
			this.setData({ //预抽取，将数组中第一个商品，也就是库存最多的保存起来，如果购买，就用这个商品id
				resultGoods: goodsArr[0]
			})
		}
		console.log('预抽取：')
		console.log(this.data.resultGoods)
		goodsArr = this.data.goodsList.filter(item => { // 将商品列表过滤掉预抽取的商品，留下本次无关商品
			return item.goods_id != this.data.resultGoods.goods_id && item.goods_name.indexOf('隐藏') == -1
		})
		console.log('与本次抽取无关商品：')
		console.log(goodsArr)
		var ListLength = goodsArr.length // 无关商品数组长度+1，
		var roll1 = Math.floor(Math.random() * ListLength) //roll一个商品
		var roll2 = Math.floor(Math.random() * ListLength) //再roll一个商品
		if (roll1 == roll2) { //如果第二个roll的和第一个重复了，再roll一遍
			roll2 = Math.floor(Math.random() * ListLength)
		}
		if (roll1 == roll2) { //如果第二个roll的和第一个重复了，再roll一遍
			roll2 = Math.floor(Math.random() * ListLength)
		}
		if (roll1 == roll2) { //如果第二个roll的和第一个重复了，再roll一遍
			roll2 = Math.floor(Math.random() * ListLength)
		}
		console.log('准备roll掉的index：' + roll1 + roll2)
		var rollGoodArr = goodsArr.filter(item => { //从商品列表roll出去的两个保存到一个新数组里，在赋值公共变量
			return item.id == goodsArr[roll1].id || item.id == goodsArr[roll2].id
		})
		console.log('roll掉的两个商品：')
		console.log(rollGoodArr)
		this.setData({
			rollGoods: rollGoodArr
		})
		wx.hideToast()
	},
	//摇一摇
	roll: function() {
		if (this.data.goodsList.length > 2) {
			if (this.data.num > 1) {
				wx.showToast({
					title: '每个盒子只能摇两次',
					icon: 'none'
				})
				return
			}
		} else if (this.data.goodsList.length > 1) {
			if (this.data.num > 0) {
				wx.showToast({
					title: '当前盒子只能摇一次',
					icon: 'none'
				})
				return
			}
		} else {
			wx.showToast({
				title: '当前盒子不能摇哦~',
				icon: 'none'
			})
			return
		}
		this.data.rollGoodsShow.push(this.data.rollGoods[this.data.num])
		wx.showToast({
			title: '这个不是' + this.data.rollGoods[this.data.num].goods_name,
			icon: 'none'
		})
		this.setData({
			rollGoodsShow: this.data.rollGoodsShow,
			num: this.data.num + 1
		})
	},
	//就拆它
	showDetail() {
		var _this = this
		if (!_this.data.show) {
			wx.showLoading({
				title: '正在打开..',
			})
			//如果存在活动ID:activity,直接领取
			if (_this.data.activity) {
				console.log('活动领取', _this.data.activity)
				wx.request({
					url: app.globalData.url+'/v1/channel/order',
					method: 'POST',
					data: {
						openid: app.globalData.openId,
						id: _this.data.activity,
						fid:_this.data.ffid
					},
					success: function(res) {
						console.log('打开成功-----')
						console.log(res)
						wx.hideLoading()
						if (res.data.code == 0) {
							wx.showToast({
								title: res.data.data,
								duration: 3000
							})
							wx.navigateTo({
								url: '/pages/order/order',
							})
						} else {
							//Toast.fail(res.data.msg);
							wx.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							})
						}
						console.log('order-------------', res)
					},
					fail: (err) => {
						console.log('打开失败-----')
						console.log(err)
						wx.hideLoading()
						wx.showToast({
							title: '打开失败',
							duration: 2000
						})
					}
				})
			} else {
				wx.request({
					url: app.globalData.url+'/v1/goods/order',
					method: 'POST',
					data: {
						goods_id: _this.data.resultGoods.goods_id
					},
					success: function(res) {
						wx.hideLoading()
						if (res.data.code == 0) {
							if (res.data.data) {
								_this.setData({
									goodsPrice: Number(res.data.data.gprice),
									boxTop: res.data.data.durl
								})
								_this.setData({
									show: true,
									showMsg: false,
									company: res.data.data.company
								})
							}
						} else {
							//Toast.fail(res.data.msg);
							wx.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							})
						}
						console.log('order-------------', res)
					},
					fail: () => {
						wx.hideLoading()
						wx.showToast({
							title: '打开失败',
							duration: 2000
						})
					}
				})
			}
		} else {
			_this.setData({
				show: false,
				showMsg: false
			})
		}
	},
	changePayType(e) {
		this.setData({
			payType: e.currentTarget.dataset.type
		})
	},
	changeBox: function() {
		this.setData({
			btnDisable: true
		})
		var _this = this
		this.setData({
			move: 1,
			showMsg: false,
			right: true
		})
		setTimeout(function() {
			_this.setData({
				move: 2,
				right: false
			})
			_this.setData({
				btnDisable: false
			})
		}, 500)
		this.randomGoods()
	},
	showMsgBox: function() {
		this.setData({
			showMsg: !this.data.showMsg
		})
	},
	confirm: function() {
		// wx.navigateTo({
		//   url: '/pages/openBox/openBox?id=123',
		// })
	},
	/*
	 *确认支付
	 */
	createOrder: function() {
		var _this = this
		_this.setData({
			loading: true
		})
		wx.request({
			url: app.globalData.url+'/v1/order/order',
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			data: {
				goods_id: _this.data.resultGoods.goods_id,
				openid: app.globalData.openId
			},
			success: function(r) {
				console.log('点击了确认支付-----', r)
				_this.setData({
					loading: false,
				})
				if (r.data.code == 0) {
					if (_this.data.payType == 'wechat') {
						_this.beforePay(r.data.data)
					} else {
						_this.balancePay(r.data.data)
					}
				} else {
					console.log('确认支付错误------', r, r.data.data.message)
					wx.showToast({
						title: r.data.data.message,
						icon: 'none',
						duration: 3000
					})
				}
			},
			fail: (err) => {
				_this.setData({
					loading: false,
				})
			}
		})
	},
	beforePay: function(data) {
		var _this = this
		wx.request({
			url: app.globalData.url+'/v1/wechat/pay',
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			data: {
				uid: data.uid,
				id: data.id,
				orderName: 'WOWSURPRISE有惊喜'
			},
			success: function(r) {
				_this.pay(r.data.data.package, data.id)
			},
			fail: (err) => {

			}
		})
	},
	pay: function(data, order) {
		console.log('pay()------data,order-------', data, order)
		var _this = this
		wx.requestPayment({
			timeStamp: data.timeStamp,
			nonceStr: data.nonceStr,
			package: data.package,
			signType: 'MD5',
			paySign: data.paySign,
			success(res) {
				var bIndex = app.globalData.bBoxIdx
				var sIndex = app.globalData.sBoxIdx
				app.globalData.boxArr[bIndex][sIndex] = 0
				if (_this.data.demolition == "1") {
					wx.navigateTo({
						url: '/pages/openBox/openBox?name=' + _this.data.resultGoods.goods_name + '&order=' + order + '&url=' +
							_this.data.boxFace
					})
					_this.setData({
						loading: false,
					})
				} else {
					wx.navigateTo({
						url: '/pages/order/order',
					})
					_this.setData({
						loading: false,
					})
				}
			},
			fail(res) {
				_this.setData({
					loading: false,
				})
				wx.showToast({
					icon: 'none',
					title: '用户取消支付',
				})
			}
		})
	},
	balancePay: function(data) {
		console.log('余额支付---------', data)
		var _this = this
		wx.request({
			url: app.globalData.url+'/v1/payment/money',
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			data: {
				openid: app.globalData.openId,
				order_code: data.order_code,
			},
			success: function(r) {
				r = r.data
				if (r.code == 0) {
					var bIndex = app.globalData.bBoxIdx
					var sIndex = app.globalData.sBoxIdx
					app.globalData.boxArr[bIndex][sIndex] = 0
					wx.showToast({
						title: r.data
					})
					setTimeout(function() {
						if (_this.data.demolition == "1") {
							wx.navigateTo({
								url: '/pages/openBox/openBox?name=' + _this.data.resultGoods.goods_name + '&order=' + data.id +
									'&url=' + _this.data.boxFace
							})
							_this.setData({
								loading: false,
							})
						} else {
							wx.navigateTo({
								url: '/pages/order/order',
							})
							_this.setData({
								loading: false,
							})
						}
					}, 1500)
				} else {
					wx.showToast({
						title: r.data.message,
						icon: 'none',
						duration: 4000
					})
					_this.setData({
						loading: false,
					})
				}
			}
		})
	},
	//点击去充值
	Recharge: (e) => {
		console.log('点击去充值按钮--------', e)
		wx.navigateTo({
			url: '/pages/recharge/recharge',
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		if (options.activity) {
			this.setData({
				activity: options.activity,
				ffid:options.ffid
			})
		}
		this.getGoodsList(options.fid)
		this.getDetail(options.fid)

		this.setData({
			mobile: app.globalData.mobile,
			ficationLOGO: app.globalData.ficationLOGO
		})
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		this.getBalance()
		//摇一摇
		const _this = this;
		_this.data.isShow = true;
		wx.onAccelerometerChange(function (e) {
		  if (!_this.data.isShow) {
		    return
		  }
		  if (e.x > 1 && e.y > 1) {
		    _this.roll()
		  }
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		this.data.isShow = false;
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
